﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using YmtAuth.Common.Cache;
using YmtAuth.Domain.Model.BlacklistUser;
using YmtAuth.Dto;
using YmtAuth.Repository.MSSQL;
using YmtSystem.CrossCutting;
using ServiceStack;
using System.Threading.Tasks;
using YmtAuth.Common.Utility;

namespace YmtAuth.AppService
{
    /// <summary>
    /// 买手在线
    /// </summary>
    public class SellerOnlineServiceAgent
    {
        private static readonly TaskQueue taskQueue = new TaskQueue();

        private static readonly LocalCache2<string, bool> SellerOnlineStatusTokenCache = new LocalCache2<string, bool>();

        public static void PostSellerOnlineLoginStatus(SellerOnlineStatusOp sellerOnlineStatusOp)
        {
            //只有买手才记录用户的登录在线状态
            if (YmatouBlacklistUserSpecifications.IsSellerOnlineSource(sellerOnlineStatusOp.AppSource))
            {
                taskQueue.EnqueueTask(
                    (obj) => SaveSellerOnlineStatus((SellerOnlineStatusOp)obj),
                    (obj, ex) => YmatouLoggingService.Error("记录买手登录在线状态出现异常, " + obj, ex),
                    sellerOnlineStatusOp
                    );
            }
        }

        //更新用户token认证在线状态
        public static void PostSellerOnlineTokenStatus(SellerOnlineStatusOp opObj)
        {
            //只有买手才记录用户的Token认证在线状态
            if (YmatouBlacklistUserSpecifications.IsSellerOnlineSource(opObj.AppSource))
            {
                string key = "{0}_{1}_{2}".Fmt(opObj.UserId, opObj.OpType, opObj.Op);

                var needUpdate = SellerOnlineStatusTokenCache.GetOrAdd(key, token => new LocalCache2<string, bool>._CacheItem
                {
                    Value = true,
                    ExpiredTime = TimeSpan.FromMinutes(1)
                }, false);

                if (needUpdate)
                {
                    YmatouLoggingService.Debug("更新买手Token在线状态，1分钟内不再更新, {0}", opObj.ToJson());
                    taskQueue.EnqueueTask(
                        (obj) => SaveSellerOnlineStatus((SellerOnlineStatusOp)obj),
                        (obj, ex) => YmatouLoggingService.Error("记录买手Token在线状态出现异常, " + obj, ex),
                        opObj
                        );

                    SellerOnlineStatusTokenCache.Replace(key, false, TimeSpan.FromMinutes(1));
                }
            }
        }


        private static void SaveSellerOnlineStatus(SellerOnlineStatusOp sellerOnlineStatusOp)
        {
            try
            {
                var dataJson = JsonConvert.SerializeObject(sellerOnlineStatusOp);

                byte[] by = Encoding.UTF8.GetBytes(dataJson);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://userservice.ymatou.com/seller/onlinestatus/op");
                httpWebRequest.ContentType = "application/json;charset=utf-8";
                httpWebRequest.Accept = "application/json;charset=utf-8";
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentLength = by.Length;
                httpWebRequest.Timeout = 30000;
                httpWebRequest.ReadWriteTimeout = 30000;

                var postStream = httpWebRequest.GetRequestStream();
                postStream.Write(by, 0, by.Length); postStream.Close();
                using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    //状态码非 200 ，返回异常信息
                    var result = streamReader.ReadToEnd();
                    ResponseData<string> res = JsonConvert.DeserializeObject<ResponseData<string>>(result);

                    YmatouLoggingService.Debug("记录用户在线状态, SaveSellerOnlineStatus: {0}, result: {1}", sellerOnlineStatusOp.ToJson(), res.ToJson());
                }
            }catch(Exception ex){
                YmatouLoggingService.Error(string.Format("记录用户在线状态异常, SaveSellerOnlineStatus error! op: {0}, msg: {1}", sellerOnlineStatusOp.ToJson(), ex.Message), ex);
                throw;
            }
        }

        ///// <summary>
        ///// 检查用户是否是需要记录“在线状态”的买手
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <param name="source"></param>
        ///// <returns></returns>
        //private static bool IsSellerOnlineUser(int userId, string source)
        //{
        //    bool returnVal = false;
        //    string msg = string.Empty;
        //    bool isSellerOnlineSource = YmatouBlacklistUserSpecifications.IsSellerOnlineSource(source);
        //    if (isSellerOnlineSource)
        //    {
        //        int userType = -1;
        //        if (userId > 0)
        //        {
        //            // var userType = RepositoryDependencies.UserRepository.Invoke().TryFindUserType(userId);

        //            userType = (int)AuthAppService.UserTypeCache.GetOrAdd(userId, uid => new LocalCache2<int, byte>._CacheItem
        //            {
        //                Value = Convert.ToByte(RepositoryDependencies.UserRepository.Invoke().TryFindUserType(uid)),
        //                ExpiredTime = TimeSpan.FromDays(1)
        //            });

        //            // userType 为1表示买手
        //            if (userType == 1)
        //            {
        //                returnVal = true;
        //            }
        //        }
        //    }

        //    return returnVal;
        //}
    }
}
